package biz.datalk.industrialland.common.validated.validator;

import biz.datalk.industrialland.common.validated.ChkInteger;
import org.apache.commons.lang3.ArrayUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author tarofang@163.com
 * @date 2024-01-24
 */
public class ChkIntegerValidator implements ConstraintValidator<ChkInteger, Integer> {

    private boolean required;
    private String message;
    private String nullMessage;
    private int[] optVal;

    @Override
    public void initialize(ChkInteger constraintAnnotation) {
        this.required = constraintAnnotation.required();
        this.message = constraintAnnotation.message();
        this.nullMessage = constraintAnnotation.nullMessage();
        this.optVal = constraintAnnotation.optVal();
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (value == null) {
            if (this.required) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate(nullMessage).addConstraintViolation();
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        }

        boolean isValid = ArrayUtils.contains(this.optVal, value);
        if (!isValid) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
        }
        return isValid;
    }
}
